package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 * 
 * @author itheima
 * @date 2025-05-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient ioTDAClient;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * @param
     * @return 结果
     */
    @Override
//    public int updateDevice(Device device)
    public void updateDevice(DeviceDto dto)
    {
//        return updateById(device) ? 1 : 0;
        //属性拷贝
        Device device = BeanUtil.toBean(dto, Device.class);
        try{
            //修改华为云
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            UpdateDevice body = new UpdateDevice();
            body.setDeviceName(device.getDeviceName());
            request.withDeviceId(device.getIotId());
            request.withBody(body);
            ioTDAClient.updateDevice(request);
            //修改数据库
            updateById(device);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("修改失败");
        }
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient  client;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 物联网平台同步产品列表到redis
     */
    @Override
    public void syncProductList() {
        //1．从I0T平台查询所有的产品列表
        ListProductsRequest request = new ListProductsRequest();
        //默认10
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        //2.解析产品列表，存入redis
        List<ProductSummary> productList = response.getProducts();
        redisTemplate.opsForValue().set(RedisKeyConstants.IOT_ALL_PRODUCT_LIST,  productList);
    }

    /**
     * 从redis查询所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从redis查询所有产品列表
        List<ProductSummary> productList = (List<ProductSummary>) redisTemplate.opsForValue().get(RedisKeyConstants.IOT_ALL_PRODUCT_LIST);
        //判断List是否为空，如果为空，则返回空集合
        if(CollUtil.isEmpty(productList)){
            return List.of();
        }

        // 注意 list拷贝选择copyToList：
        List<ProductVo> voList = BeanUtil.copyToList(productList, ProductVo.class);
        return voList;
    }


    /**
     * 注册设备
     */
    @Override
    public void register(DeviceDto dto) {
        //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        long countName = count(
                new LambdaQueryWrapper<Device>()
                        .eq(StrUtil.isNotBlank(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName())
        );
        if (countName > 0){
            //如果重复，抛出异常，终止运行
            throw new RuntimeException("设备名称重复");
        }

        //2.检验设备标识码nodeId是否重复
        long countNodeId = count(
                new LambdaQueryWrapper<Device>()
                        .eq(StrUtil.isNotBlank(dto.getNodeId()), Device::getNodeId, dto.getNodeId())
        );
        if ( countNodeId > 0){
            throw new RuntimeException("设备标识码重复");
        }
        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品(产品唯一标识)
        long countProduct = count(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getLocationType, dto.getLocationType())
                        .eq(Device::getBindingLocation, dto.getBindingLocation())
                        .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                        .eq(Device::getProductKey, dto.getProductKey())
        );
        if (countProduct > 0){
            throw new RuntimeException("同一位置绑定了同一类产品");
        }

        //4.在iot平台中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());

        // 设置设备的秘钥
        String scret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(scret);
        body.withAuthInfo(authInfo);
        request.withBody(body);

        // 发送请求
        String iotId = "";
        try {
            AddDeviceResponse response = client.addDevice(request);
            iotId = response.getDeviceId();
        }catch (Exception e){
            // 抛出异常 终止运行‘
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        //5.设备数据保存到数据库
        // 对象属性拷贝
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(scret);
        device.setIotId(iotId);
        // 保存
        save(device);
    }

    /**
     * 3.5.7 查询设备详细数据
     * @param iotId
     * @return
     */

    @Override
    public DeviceDetailVo showDeviceDetail(String iotId) {
        //1.先查询询IOT平台，得到设备详情：设备状态、激活时间
        ShowDeviceRequest request =new ShowDeviceRequest();
        request.withDeviceId(iotId);
        String deviceStatus ="";
          String activeTimeStr="";
        try{
            ShowDeviceResponse response = client.showDevice(request);

            //设备状态、激活时间
            deviceStatus = response.getStatus();
            activeTimeStr= response.getActiveTime();
        }catch (Exception e){
            //如果有异常，终止运行
            e.printStackTrace();
            throw new BaseException("物联网接口－查询设备详情，调用失败");
        }
        //2.再查数据库设备表，得到设备详情
        Device device = getOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, iotId)
            );

        //3组装vo返回
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(deviceStatus);

        //需要单独的组装时间
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(activeTime);
        }
        return vo;
    }


    /**
     * 查看设备上报的数据
     */
    @Override
    public List<Map> queryServiceProperties(String iotId) {
        // 1. 先查询IOT平台，得到设备最新上报的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);

        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);
            // 2. 解析响应数据
            Object properties = response.getShadow()
                    .get(0)
                    .getReported()
                    .getProperties();
            // json对象
            JSONObject jsonObject = JSONUtil.parseObj(properties);

            // 上报时间
            String eventTimeStr = response.getShadow().get(0).getReported().getEventTime();

            // 3. 封装数据：
            List list = new ArrayList<>();

            // 需要对日期格式进行单独处理
            //处理上报时间日期
            LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            jsonObject.forEach((key, value) -> {
                Map<String, Object> map = new HashMap<>();
                map.put("functionId", key);
                map.put("value", value);
                map.put("eventTime", eventTime);

                list.add(map);
            });
            return list;

        } catch (Exception e) {
            // 如果有异常，终止运行
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查看设备上报的数据，调用失败");
        }
    }


    /**
     * 查询产品详情服务-属性(报警规则模块使用)
     */

    @Override
    public AjaxResult queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)){
            throw new BaseException("产品标识不能为空");
        }

        //1.根据产品的标识查询IOT平台 产品的详情数据
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);

        List<ServiceCapability> serviceCapabilities;//变量抽取到key之外
        //远程调用有可能有异常，加上try catch
        try {
            ShowProductResponse response = client.showProduct(request);

            //2. 解析结果并返回
            serviceCapabilities=response.getServiceCapabilities();
        }catch (Exception e){
            //抛出异常
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询产品详情服务-属性，调用失败");
        }


        //3. 处理好空检验
        if (CollUtil.isEmpty(serviceCapabilities)){
            return  AjaxResult.success(List.of());
        }
        return AjaxResult.success(serviceCapabilities);

    }
}
